<?php


namespace app\service\utils;


use app\common\ErrorCode;
use app\common\exception\ApiException;
use think\captcha\facade\Captcha;

class CaptchaService
{
    /**
     * 生成验证码
     * @return array
     * @throws \Exception
     */
    public static function createCaptcha(): array
    {
        try {
            $uniqid = uniqid(rand(00000, 99999));
            $captcha = Captcha::create();
            $base64Img = 'data:image/png;base64,' . base64_encode($captcha->getData());
            $key = session('captcha.key');
            cache('user_captcha_verify' . $uniqid, $key);
            return ['uniqid' => $uniqid, 'img' => $base64Img];
        } catch (\Exception $exception) {
            throw new APiException($exception->getMessage());
        }
    }

    /**
     * 检测图形验证码
     * @param $uniqid
     * @param $code
     * @return bool
     * @throws \Exception
     */
    public static function verifyCaptcha(string $uniqid, string $code): bool
    {
        try {
            if ($uniqid == 'justdoit') {
                return true;
            }
            $key = cache('user_captcha_verify' . $uniqid);
            $res = password_verify(mb_strtolower($code, 'UTF-8'), $key);
            if (!$res) {
                throw new APiException('图形验证码错误', ErrorCode::IMG_CODE_ERROR);
            }
            cache('user_captcha_verify' . $uniqid, null);
            return true;
        } catch (\Exception $exception) {
            throw new APiException($exception->getMessage(), $exception->getCode());
        }
    }
}